package com.example.demo.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.example.demo.dto.MenuDto;
import com.example.demo.mapper.MenuMapper;
import com.example.demo.po.Menu;
import com.example.demo.po.MenuExample;
import com.example.demo.service.MenuService;

@Service
public class MenuServiceImpl implements MenuService{

	@Autowired
	private MenuMapper menuMapper;
	
	@Override
	public void insert(Menu t) {
		// TODO Auto-generated method stub
		menuMapper.insert(t);
	}

	@Override
	public void update(Menu t) {
		// TODO Auto-generated method stub
		menuMapper.updateByPrimaryKey(t);
	}

	@Override
	public void delete(int id) {
		// TODO Auto-generated method stub
		menuMapper.deleteByPrimaryKey(id);
	}

	@Override
	public Menu selectById(int id) {
		// TODO Auto-generated method stub
		return menuMapper.selectByPrimaryKey(id);
	}

	@Override
	public List<Menu> selectAll() {
		// TODO Auto-generated method stub
		return menuMapper.selectByExample(null);
	}

	@Override
	public List<MenuDto> selectByFid(int fid) {
		// TODO Auto-generated method stub
		List<Menu> menus=new ArrayList<Menu>();
		menus=menuMapper.selectByExample(null);
		List<MenuDto> menuDTOs=new ArrayList<MenuDto>();
		for(Menu menu:menus) {
			if(menu.getFid()==0) {
				MenuDto item=new MenuDto();
				item.setId(menu.getId());
				item.setName(menu.getName());
				item.setFid(menu.getFid());
				item.setUrl(menu.getUrl());
				for(Menu menu2:menus) {
					if(menu2.getFid()==item.getId()) {
						MenuDto item2=new MenuDto();
						item2.setId(menu2.getId());
						item2.setName(menu2.getName());
						item2.setFid(menu2.getFid());
						item2.setUrl(menu2.getUrl());
						item.getChildMenu().add(item2);
					}
				}
				menuDTOs.add(item);
			}
		}
		return menuDTOs;
	}

	@Override
	public List<MenuDto> getAllMenu() {
		// TODO Auto-generated method stub
		List<Menu> menus=new ArrayList<Menu>();
		menus=menuMapper.selectByExample(null);
		List<MenuDto> menuDTOs=new ArrayList<MenuDto>();
		for(Menu menu:menus) {
			if(menu.getFid()==0) {
				MenuDto item=new MenuDto();
				item.setId(menu.getId());
				item.setName(menu.getName());
				item.setFid(menu.getFid());
				item.setUrl(menu.getUrl());
				for(Menu menu2:menus) {
					if(menu2.getFid()==item.getId()) {
						MenuDto item2=new MenuDto();
						item2.setId(menu2.getId());
						item2.setName(menu2.getName());
						item2.setFid(menu2.getFid());
						item2.setUrl(menu2.getUrl());
						item.getChildMenu().add(item2);
					}
				}
				menuDTOs.add(item);
			}
		}
		return menuDTOs;
	}

	public List<Menu> getMenu(){
		MenuExample example = new MenuExample();
		MenuExample.Criteria criteria = example.createCriteria();
		criteria.andFidEqualTo(0);
		return menuMapper.selectByExample(example);
	}
}
